package com.example.smoke;


import static com.example.smoke.FunctionActivity.imageUri;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

public class ResultActivity extends AppCompatActivity {
    ImageView iv;
    TextView tv;
    Button btnShare;
    Button btnBack;
    View mShareImg;
    CheckBox cb;
    String recordNum;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);

        iv = findViewById(R.id.iv);
        tv = findViewById(R.id.tv);
        btnShare = findViewById(R.id.btnShare);
        btnBack = findViewById(R.id.btnBack);
        cb=findViewById(R.id.cb);
        btnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View rootView = getWindow().getDecorView().getRootView();
                rootView.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(rootView.getDrawingCache());
                File outputImage = new File(getExternalCacheDir(), "smoke.jpg");
                if (outputImage.exists()) {
                    outputImage.delete();
                }
                try {
                    outputImage.createNewFile();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                FileOutputStream outputStream;
                try {
                    outputStream = new FileOutputStream(outputImage);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }

                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(ResultActivity.this, "com.example.smoke.fileprovider", outputImage);
                } else {
                    imageUri = Uri.fromFile(outputImage);
                }
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType("image/*");
                shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
                Intent chooserIntent = Intent.createChooser(shareIntent, "分享截图");
                startActivity(chooserIntent);
            }
        });
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)
                {
                    float a=Float.parseFloat(recordNum);
                    a-=0.25;
                    DecimalFormat decimalFormat = new DecimalFormat("#.##");
                    String formattedNumber = decimalFormat.format(a);
                    tv.setText("黑度：" + formattedNumber);
                }
                else
                {
                    tv.setText("黑度：" + recordNum);
                }
            }
        });
        //计算黑度，思路是直接计算截取部分的整体亮度，误差很大
        Bitmap originalBitmap;
        try {
            originalBitmap = getBitmapFromUri(imageUri);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Bitmap grayscaleBitmap = toGrayscale(originalBitmap);
        int averageBrightness = calculateAverageBrightness(grayscaleBitmap);
        float blackness = 5 - (float) averageBrightness / 51;
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        String formattedNumber = decimalFormat.format(blackness);
        recordNum=formattedNumber;
        iv.setImageBitmap(originalBitmap);
        tv.setText("黑度：" + formattedNumber);
    }

    //先把图片转成灰度图
    public Bitmap toGrayscale(Bitmap bmpOriginal) {
        int width, height;
        height = bmpOriginal.getHeight();
        width = bmpOriginal.getWidth();

        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmpGrayscale);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmpOriginal, 0, 0, paint);

        return bmpGrayscale;
    }

    //计算截取部分的平均灰度
    public int calculateAverageBrightness(Bitmap bmp) {
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        int pixelCount = width * height;

        int totalBrightness = 0;

        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                int pixel = bmp.getPixel(i, j);
                int brightness = (int) (Color.red(pixel) * 0.299 + Color.green(pixel) * 0.587 + Color.blue(pixel) * 0.114);
                totalBrightness += brightness;
            }
        }

        int averageBrightness = totalBrightness / pixelCount;
        return averageBrightness;
    }

    public Bitmap getBitmapFromUri(Uri uri) throws IOException {
        InputStream input = getContentResolver().openInputStream(uri);
        return BitmapFactory.decodeStream(input);
    }
    private File saveScreenshot(Bitmap bitmap) {
        File screenshotFile = new File(getExternalFilesDir(null), "screenshot.png");
        try {
            FileOutputStream outputStream = new FileOutputStream(screenshotFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            return screenshotFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}